import json
import re
import requests
from lxml import etree

from crawler_core.exception.unknown_exec import UnknownException
from down_server.interface_download import DownloadResume
from down_server.template.template_51job import Property51job
from lib.sys.logger_factory import LoggerFactory
from crawler_core.constant.constants import Constants
from crawler_core.constant.constants_api import ConstantAPI
from crawler_core.exception.cookies_exec import CookieException


class Job51DownloadResume(DownloadResume):
    logger = LoggerFactory.getLogger("Job51DownloadResume", "download")

    def __init__(self):
        pass

    def download(self, context, cookies):
        s = requests.Session()
        for cookie in cookies:
            s.cookies.set(cookie["name"], cookie["value"])
        url = context['url']
        _url = re.sub('ehire.51job.com/ResumeView.aspx', 'ehire.51job.com/Candidate/ResumeView.aspx', url)
        try:
            data = self.get(s, _url)
        except CookieException:
            Job51DownloadResume.logger.info("Job51DownloadResume 执行下载 cookies 失效...")
            data = {Constants.DOWNLOAD_CODE: ConstantAPI.RETURN_ERROR_COOKIES}
        except UnknownException as e:
            Job51DownloadResume.logger.info("Job51DownloadResume 执行下载 cookies 失效...")
            data = {
                Constants.DOWNLOAD_CODE: ConstantAPI.RETURN_ERROR_UNKNOWN,
                Constants.DOWNLOAD_MSG: json.dumps(e)
            }
        return data

    def get(self, s, url):
        results = re.match("[\s\S]+?hidUserID=([\d]+)[\s\S]+?hidKey=([\s\S]+)", url)
        user_id = results.group(1)
        # 1、请求下载
        Job51DownloadResume.logger.info("Job51DownloadResume ---地址---url:%s ..." % url)
        data1 = {"doType": 'SearchToCompanyHr', "userId": user_id}
        headers = Property51job.header
        try:
            Job51DownloadResume.logger.info("Job51DownloadResume 下载简历[1], 请求下载  ...")
            response1 = s.post(Property51job.download_url, data=data1, headers=headers, allow_redirects=False,
                               verify=False)
            Job51DownloadResume.logger.info(
                "Job51DownloadResume ---response1.status_code%s  ..." % response1.status_code)
        except BaseException as e:
            Job51DownloadResume.logger.info("Job51DownloadResume 下载简历[1], 下载失败  ...")
            # 判断下载异常
            Job51DownloadResume.logger.info('下载简历失败异常的问题 -- %s' % e)
            raise UnknownException(e.args, e)
        if response1.status_code != 200:
            raise CookieException()
        # 2、执行下载
        hid_key = results.group(2)
        data2 = {"hidCheckKey": hid_key, "hidCheckUserIds": user_id}

        Job51DownloadResume.logger.info("Job51DownloadResume 下载简历[2],数据请求%s %s  ..." % (hid_key, user_id))
        try:
            Job51DownloadResume.logger.info("Job51DownloadResume 下载简历[2], 执行下载  ...")
            response2 = s.post(url=url, data=data2, headers=headers, allow_redirects=False, verify=False)
            Job51DownloadResume.logger.info(
                "Job51DownloadResume ---response2.status_code %s  ..." % response2.status_code)
        except BaseException as e:
            Job51DownloadResume.logger.info("Job51DownloadResume 下载简历[2], 下载失败  ...")
            # 判断下载异常
            Job51DownloadResume.logger.info('下载简历失败异常的问题 -- %s' % e)
            raise UnknownException(e.args, e)

        if response2.status_code != 200:
            raise CookieException()
        data = {
            Constants.CACHE_DOWNLOAD_DATA: response2.text, Constants.DOWNLOAD_CODE: ConstantAPI.RETURN_SUCCESS
        }
        return data
